<template>
  <div class="login_wrap">
    <el-form
      :model="loginForm"
      status-icon
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      v-if="!isLogin"
    >
      <el-form-item label="账号：">
        <el-input v-model="loginForm.username" type="text"></el-input>
      </el-form-item>
      <el-form-item label="密码：">
        <el-input v-model="loginForm.password" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="btnLogin()" type="primary">提交</el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
    <div v-if="isLogin">
      <el-button round @click="logout_btn">退出登录</el-button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginForm: {
        username: 'xiaoming',
        password: '123456'
      },
      isLogin: false
    }
  },
  mounted() {
    this.getIsLogin()
  },
  methods: {
    // 点击退出登录
    logout_btn() {
      sessionStorage.removeItem('isLogin', 'token', 'user_id', 'username')
      location.reload()
    },
    // 获取登录状态
    getIsLogin() {
      this.isLogin = sessionStorage.getItem('isLogin')
    },
    // 点击登录
    btnLogin: async function() {
      var { data: res } = await this.$http.post(
        'http://localhost:3000/api/users/login',
        {
          username: this.loginForm.username,
          password: this.loginForm.password
        }
      )
      if (res.msg === '登录成功') {
        // 登录成功，将token存储到本地
        sessionStorage.setItem('token', res.token)
        sessionStorage.setItem('isLogin', true)
        sessionStorage.setItem('username', res.username)
        sessionStorage.setItem('user_id', res.id)
        this.$router.push({ path: '/index' })
        location.reload()
      } else {
        console.log('登录失败')
        sessionStorage.setItem('isLogin', false)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.login_wrap {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}
</style>
